/**
 * 
 */
package com.ytkj.digitalConstruction.service.base;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件管理类
 * 
 * @author laupete
 * @date 2017年8月15日
 * @description
 *
 */
@Service
public class FileService {
	private static final Logger logger = LoggerFactory.getLogger(FileService.class);

	@Value("${web.head.showpath}")
	private String templateUrl;

	private final ResourceLoader resourceLoader;

	@Autowired(required = true)
	public FileService(ResourceLoader resourceLoader) {
		this.resourceLoader = resourceLoader;
	}

	/**
	 * 获取文件
	 * 
	 * @param fileName
	 * @return
	 */
	public Resource getResource(String fileName) {
		Path path = Paths.get(templateUrl, fileName);
		return resourceLoader.getResource("file:" + path.toString());
	}

	/**
	 * 保存文件
	 * 
	 * @param file
	 * @updateBy 宁煜
	 * @return 
	 */
	public boolean saveResource(MultipartFile file, String fileName, String path) {
		boolean result = true;
		if (!file.isEmpty()) {
			try {
				File fileDir = new File(path);
				if(!fileDir.exists()) {
					fileDir.mkdirs();
				}
				Files.copy(file.getInputStream(), Paths.get(path, fileName));
			} catch (IOException | RuntimeException e) {
				result = false;
				logger.error("Resource save error, message: {}", e.getMessage());
			}
		}
		return result;
	}

	/**
	 * 获取资源路径
	 * 
	 * @return
	 */
	public String getResourcePath() {
		return templateUrl;
	}

}
